<template>
  <div class="component-upload-image">
    <el-upload
      ref="uploadRef"
      :class="['upload-file-uploader', overLimit ? 'hide-upload-btn' : '']"
      :multiple="limit !== 1"
      :action="uploadImgUrl"
      :data="extraData"
      :headers="headers"
      :limit="limit"
      :disabled="disabled"
      :file-list="fileList"
      list-type="picture-card"
      :show-file-list="true"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-preview="previewShow"
    >
      <i class="el-icon-plus"></i>
      <!-- 上传提示 -->
      <template #tip>
        <div class="el-upload__tip" v-if="showTip">
          请上传
          <template v-if="min > 0 && limit > 0">
            <template v-if="min === limit"><b style="color: #f56c6c">{{ limit }}</b>张</template>
            <template v-else><b style="color: #f56c6c">{{ min }}-{{ limit }}</b>张</template>
          </template>
          <template v-else-if="min > 0">至少<b style="color: #f56c6c">{{ min }}</b>张</template>
          <template v-else-if="limit > 0">最多<b style="color: #f56c6c">{{ limit }}</b>张</template>
          <template v-if="fileSize">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
          <template v-if="fileTypeList">格式为 <b style="color: #f56c6c">{{ fileTypeList.join('/') }}</b></template>
          的图片
        </div>
      </template>

    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800px" append-to-body @close="previewClose">
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/user"
import { UPLOADER, RESPONSE } from '@/config'
import { getFileName, getFileExt } from '@/utils/tools/url'
import { staticUrl } from '@/utils/frame'

export default {
  props: {
    defaultList: [String, Array], // 默认列表
    value: [String, Object, Array],
    // 返回结果类型，默认false字符串， true返回数组 {name:xx,url:xxx}
    resultArray: Boolean,
    disabled: Boolean, // 是否禁用状态
    size: String, // 展示大小 small 或 空
    button: String, // 上传按钮名称
    overHideUpload: Boolean, // 上传超过数量是否隐藏上传按钮
    extraData: Object, // 上传额外操作
    min: Number, // 最少数量
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
       type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      uploadImgUrl: UPLOADER.IMAGE, // 上传文件服务器地址
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      uploadList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  watch: {
    defaultList: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : val.split(',')
          // 然后将数组转为对象数组
          let temp = 1
          this.fileList = list.map(item => {
            if (typeof item === 'string') item = { name: getFileName(item), path: item }
            item.url = staticUrl(item.path)
            item.uid = item.uid || new Date().getTime() + temp++
            return item
          })
        } else {
          this.fileList = []
        }
        this.uploadList = JSON.parse(JSON.stringify(this.fileList))
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
    // 计算是否超过限制
    overLimit() {
      if (this.disabled) return true
      if (this.limit < 1 || !this.overHideUpload) return false
      return this.uploadList.length >= this.limit
    },
    // 计算获取上传文件类型后缀限制
    fileTypeList() {
      if (this.fileType && this.fileType.length) {
        if (this.fileType[0] === '*') return ['jpg', 'jpeg', 'png', 'gif']
        return this.fileType
      }
      return ['jpg', 'jpeg', 'png', 'gif']
    }
  },
  methods: {
    // 文件个数超出，
    handleExceed() {
      this.$modal.msgError(`上传图片数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(_, file) {
      this.$modal.msgError((file?.name || '图片') + " 上传失败")
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      if (this.disabled) {
        this.$modal.msgError('当前不支持上传操作')
        return false
      }
      // 校检文件类型
      if (this.fileTypeList.length) {
        const fileExt = getFileExt(file.name, true)
        if (!this.fileTypeList.includes(fileExt)) {
          this.$modal.msgError(`图片格式不正确，请上传${this.fileTypeList.join('/')}格式文件!`)
          return false
        }
      } else if (file.type.indexOf('image') === -1) {
        this.$modal.msgError(`请上传图片格式图片!`)
        return false
      }

      // 校检文件名是否包含特殊字符
      if (file.name.includes(',')) {
        this.$modal.msgError('图片名不正确，不能包含英文逗号!')
        return false
      }

      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },
    // 监听 文件新增、成功、失败
    handleChange(_, fileList){
      const uploading = fileList.some(item =>{
        return item.status !== 'success' && item.status !== 'fail'
      })
      this.uploadList = fileList

      let okList = []
      fileList.map(item => {
        if (item.status === 'success') okList.push({ name: item.name, path: item.path })
      })
      this.$emit('update:uploading', uploading)
      this.emitValue(okList)
    },
    // 监听文件删除
    handleRemove(file, fileList){
      this.handleChange(file, fileList)
    },
    // 自定义删除文件
    removeClick(file) {
      this.$refs.uploadRef.handleRemove(file)
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === RESPONSE.SUCCESS_CODE) {
        file.url = res.data.url
        file.path = res.data.path
      } else {
        this.$modal.msgError(file.name + (res?.msg || '上传失败'))
        this.removeClick(file)
      }
    },
    emitValue(fileList) {
      if (this.resultArray) {
        const result = fileList.map(item => {
          return { name: item.name, path: item.path }
        })
        this.$emit('input', result)
      } else {
        this.$emit('input', this.listToString(fileList))
      }
    },
    // 预览
    previewShow(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    previewClose() {
      this.dialogImageUrl = ''
      this.dialogVisible = false
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let result = ''
      separator = separator || ','
      list.map(item => {
        if (item.path) result += item.path + separator
      })
      return result ? result.slice(result, result.length - 1) : ''
    }
  }
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
    display: none;
}

.hide-upload-btn {
  ::v-deep.el-upload {
    display: none;
  }
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
    transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>

